package com.cysion.study.ui.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.widget.BitmapUtil
import com.cysion.study.widget.FileUtils
import com.cysion.study.widget.FlowLayoutForPulish
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.downmenu.MenuItem
import com.cysion.study.widget.downmenu.SimpleDropDownMenu
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import com.winfo.photoselector.PhotoSelector
import com.winfo.photoselector.PhotoSelector.SELECT_RESULT
import kotlinx.android.synthetic.main.activity_pinfo.*
import org.json.JSONObject
import java.io.*
import java.util.*

class PInfoActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_pinfo
    }

    private var ifPersonInfo = ""//家教中个人信息介绍：0、代表未完善；1、代表已完善
    override fun initView() {
        ifPersonInfo = intent.extras.getString("ifPersonInfo")
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("个人信息")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        //家教中个人信息介绍：0、代表未完善；1、代表已完善
        if (ifPersonInfo == "1") {
            getTeacherData()
        } else {
            fl_pics.setShowData(false, selectPics, false,false)
        }

        tv_submit.setOnClickListener(this)
        iv_head.setOnClickListener(this)

        initDropDownMenu()
        iv_sex.setOnClickListener(this)

        initFlowLayoutForPulishListener()
    }

    private fun getTeacherData() {
        Alert.loading(self)
        ApiClient.api.getTeacherInfos(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
//                        UserCache.save(it)

                    /* private var feduName=""//家教中的姓名
                     private var feduSex=""//家教中的性别
                     private var feduSchool=""//家教中的学校
                     private var feduGrade=""//家教中的学历
                     private var feduCareer=""//家教中的职业
                     private var feduSuc=""//家教中的成就
                     private var feduIntro=""//家教中的自我介绍
                     private var feduImages=""//家教中的图片*/
                    feduName = it.feduName
                    feduSex = it.feduSex
                    feduSchool = it.feduSchool
                    feduGrade = it.feduGrade
                    feduCareer = it.feduCareer
                    feduSuc = it.feduSuc
                    feduIntro = it.feduIntro
                    feduImages = it.feduImages

                    et_name.setText(it.feduName)
                    if (it.feduSex == "0") {
                        tv_sex.text = "未知"
                    } else if (it.feduSex == "1") {
                        tv_sex.text = "男"
                    } else if (it.feduSex == "2") {
                        tv_sex.text = "女"
                    }
                    et_school.setText(it.feduSchool)

                    sm_study.setTitleItem(MenuItem(0, it.feduGrade, ""))
                    sm_iden.setTitleItem(MenuItem(0, it.feduCareer, ""))
                    et_good.setText(it.feduSuc)
                    et_info.setText(it.feduIntro)


                    var imgUrl = it.feduImages
                    if (!TextUtils.isEmpty(imgUrl)) {
                        var strs = imgUrl.split(",") as MutableList
                        Glide.with(self).load(strs[0]).apply(
                            RequestOptions().placeholder(R.mipmap.default_head)
                        ).into(iv_head)
                        tv_imgnum.text = "轮播图（" + strs.size + "/10)"
                        for ((index, obj) in strs.withIndex()) {
                            selectPics.add(obj)
//                            fl_pics.addLocationPic(index, false, obj)//显示图片
                        }
                    }
                    fl_pics.setShowData(false, selectPics, false,true)

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    var studyList = mutableListOf<MenuItem>()
    var studytitle: MenuItem = MenuItem(0, "请选择学历", "")

    var feduCareerList = mutableListOf<MenuItem>()
    var feduCareertitle: MenuItem = MenuItem(0, "请选择学历", "")
    private fun initDropDownMenu() {
        sm_study.showImgIcon(false)//学历
        sm_study.setOnClickListener(this)
        studyList.add(MenuItem(0, "专科", "1"))
        studyList.add(MenuItem(0, "本科", "2"))
        studyList.add(MenuItem(0, "硕士", "3"))
        studyList.add(MenuItem(0, "博士", "4"))
        sm_study.addMenuItemForTitle(studyList, studytitle)
        sm_study.menuItemClickListener = object : SimpleDropDownMenu.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                sm_study.setTitleItem(
                    MenuItem(
                        0,
                        studyList.get(position).itemTitle,
                        studyList.get(position).itemId
                    )
                )
                feduGrade = studyList.get(position).itemTitle
            }
        }


        sm_iden.showImgIcon(false)//身份 成就
        sm_iden.setOnClickListener(this)
        feduCareerList.add(MenuItem(0, "在职", "1"))
        feduCareerList.add(MenuItem(0, "学生", "2"))
        feduCareerList.add(MenuItem(0, "专职家教", "3"))
        feduCareerList.add(MenuItem(0, "自由职业", "4"))
        sm_iden.addMenuItemForTitle(feduCareerList, feduCareertitle)
        sm_iden.menuItemClickListener = object : SimpleDropDownMenu.OnMenuItemClickListener {
            override fun onMenuItemClickListener(v: View, position: Int) {
                sm_iden.setTitleItem(
                    MenuItem(
                        0,
                        feduCareerList.get(position).itemTitle,
                        feduCareerList.get(position).itemId
                    )
                )
                feduCareer = feduCareerList.get(position).itemTitle
            }
        }


    }


    private var feduName = ""//家教中的姓名
    private var feduSex = ""//家教中的性别
    private var feduSchool = ""//家教中的学校
    private var feduGrade = ""//家教中的学历
    private var feduCareer = ""//家教中的职业
    private var feduSuc = ""//家教中的成就
    private var feduIntro = ""//家教中的自我介绍
    private var feduImages = ""//家教中的图片
    private fun submitInfo() {
        /*if (TextUtils.isEmpty(headImageUrl)) {
            ShowToast("请上传头像")
            return
        }*/
        et_name.checkBlank("请填写家教姓名") ?: return
        feduName = et_name.text.toString().trim()
        if (feduName.length < 2||feduName.length>10) {
            ShowToast("姓名输入框请输入2-10字符")
            return
        }
        et_school.checkBlank("请填写家教毕业学校") ?: return
        feduSchool = et_school.text.toString().trim()
        if (feduSchool.length < 2||feduSchool.length>40) {
            ShowToast("毕业学校请输入2-40个字符")
            return
        }
//        et_good.checkBlank("请填写成就") ?: return
        et_info.checkBlank("请填写介绍") ?: return


        feduSuc = et_good.text.toString().trim()
        if (!TextUtils.isEmpty(feduSuc)) {
            if (feduSuc.length > 500) {
                ShowToast("所获成就最多输入500字")
                return
            }
        }
        feduIntro = et_info.text.toString().trim()
        if (TextUtils.isEmpty(feduSex)) {
            ShowToast("请选择性别")
            return
        }
        if (TextUtils.isEmpty(feduGrade)) {
            ShowToast("请选择学历 ")
            return
        }
        if (TextUtils.isEmpty(feduCareer)) {
            ShowToast("请选择职业")
            return
        }

        var sb = StringBuilder()
        val pics = ArrayList<String>()
        if (selectPics != null && selectPics.size > 0) {
            for (im in selectPics) {
                sb.append("," + im)
            }
            if (sb.length > 0) {
                sb.deleteCharAt(0)
            }
            feduImages = sb.toString()
            pics.add(feduImages)
            println("###图片地址=" + feduImages)
        } else {
            feduImages = ""
        }
        if (TextUtils.isEmpty(feduImages)) {
            ShowToast("请上传个人照片及展示图片")
            return
        }
        println("###所获成就参数=" + feduSuc)

        Alert.loading(self)
        ApiClient.api.teacherSetInfo(
            UserCache.token,
            feduName,
            feduSex,
            feduSchool,
            feduGrade,
            feduCareer,
            feduSuc,
            feduIntro,
            feduImages
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("提交成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }


    }

    /*override fun outputBitmap(bitmap: Bitmap?, path: String?) {
        super.outputBitmap(bitmap, path)
        if (TextUtils.isEmpty(path)) {
            return
        }
//        headUrl = path.toString()
        println("上传头像 url="+ path)
        uploadPic(File(path))
    }*/
    private var index = 0

    private fun uploadPic(headUrl: File) {
        val params = RequestParams()
        params.put("file", headUrl)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        var url = Urls.uploadPicture

        /*ApiClient.api.upload(UserCache.token,headUrl).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    println("上传图片返回=${it}")

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }*/
        println("上传图片==" + url + "参数=" + params.toString())
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                response: JSONObject?
            ) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                hideWaitDialog()
                try {
                    if (response?.getString("code") == "0") {
                        okNum++
                        if (localPics.size == okNum) {
                            hideWaitDialog()
                        }
                        println("上传图片返回=${response.getString("data")}")
                        if (isHead) {
                            Glide.with(self).load(response.getString("data")).apply(
                                RequestOptions().placeholder(R.mipmap.default_head)
                            ).into(iv_head)
                            if (selectPics.size > 0) {
                                selectPics.removeAt(0)
                            }
                            selectPics.add(0, response.getString("data"))
                        } else {
                            selectPics.add(response.getString("data"))//把图片添加到list
                        }
                        if (selectPics.size > 0) {
                            index = selectPics.size + 1
                        }
//                        fl_pics.addLocationPic(index, false, response.getString("data"))//显示图片
                        tv_imgnum.text = "轮播图（" + selectPics.size + "/10)"
                        if (selectPics.size >= 10) {
                            fl_pics.setShowData(true, selectPics, false,true)
                        } else {
                            fl_pics.setShowData(false, selectPics, false,true)
                        }

                        index++
                    } else {
                        ShowToast("上传失败")
                        hideWaitDialog()
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    ShowToast("数据异常")
                    hideWaitDialog()
                }
            }

            override fun onFinish() {
                Alert.close()
                hideWaitDialog()
            }

            override fun onFailure(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                responseString: String?,
                throwable: Throwable?
            ) {
                super.onFailure(statusCode, headers, responseString, throwable)
                println("####上传失败" + statusCode + "##=" + responseString)
                ShowToast("上传失败")
                hideWaitDialog()
                Alert.close()
            }
        })
    }


    private var selectPics = ArrayList<String>()
    private var localPics = ArrayList<String>()
    private fun initFlowLayoutForPulishListener() {
//        fl_pics.setShow(false)

        fl_pics.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (selectPics.size >= 10) {
                    ShowToast("最多不能超过10张图片")
                    return
                }
                isHead = false
//                takePhoto()
                photoSelector()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
                if (selectPics.size == 1) {
                    selectPics.clear()
                    Glide.with(self).load("").apply(
                        RequestOptions().placeholder(R.mipmap.default_head)
                    ).into(iv_head)
                } else {
                    selectPics.remove(item.path)
//                    selectPics.removeAt(item.index)
                    Glide.with(self).load(selectPics[0]).apply(
                        RequestOptions().placeholder(R.mipmap.default_head)
                    ).into(iv_head)
                }
                tv_imgnum.text = "轮播图（" + selectPics.size + "/10)"
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
    }

    private fun photoSelector() {
        //多选(最多9张)
        PhotoSelector.builder()
            .setShowCamera(false)//显示拍照
            .setMaxSelectCount(10-selectPics.size)//最大选择9 默认9，如果这里设置为-1则是不限数量
//            .setSelected(localPics)//已经选择的照片
            .setGridColumnCount(3)//列数
            .setMaterialDesign(true)//design风格
            .setToolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//toolbar的颜色
            .setBottomBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//底部bottombar的颜色
            .setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))//状态栏的颜色
            .start(
                this,
                103
            )//当前activity 和 requestCode，不传requestCode则默认为PhotoSelector.DEFAULT_REQUEST_CODE

    }

    private var okNum = 0
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 103 && resultCode == Activity.RESULT_OK) {
            localPics.clear()
            var lPics = ArrayList<String>()
            lPics.clear()
            var protraitPath = ""
            lPics.addAll(data?.getStringArrayListExtra(SELECT_RESULT) as ArrayList<String>)
            println("###选择返回=" + lPics.size)
            if (lPics.size > 0) {
                for (pic in lPics) {
                    protraitPath = compressImage(pic)
                    localPics.add(protraitPath)
                }
            }

//            localPics = data?.getStringArrayListExtra(SELECT_RESULT) as ArrayList<String>
            println("###返回压缩后=" + localPics.size)
            /*var total=selectPics.size.toInt()+localPics.size.toInt()
            tv_imgnum.text="轮播图（"+total+"/10)"
            if (total == 10) {
                fl_pics.setShowData(true,localPics,true)
            } else {
                fl_pics.setShowData(false,localPics,true)
            }*/
            showWaitDialog("上传中...", false)
            for (obj in localPics) {
                println("###图片返回=" + obj)
                uploadPic(File(obj))
            }
        }
    }

    fun compressImage(picFileName: String): String {
        val bitmap = BitmapUtil.decodeFile(picFileName, 960)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 90f
        while (baos.toByteArray().size / 1024 > 200 && options > 80) { // 循环判断如果压缩后图片
            baos.reset()// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options.toInt(), baos)// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5f// 每次都减少10
        }
        val file = FileUtils.createFileWithSuffix(".jpg", this)
        println("压缩后大小 " + baos.toByteArray().size / 1024 + "==options=" + options)
        // 保存新文件
        try {
            val out = FileOutputStream(file)
            out.write(baos.toByteArray())
            out.flush()
            out.close()
            return file.getAbsolutePath()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return ""
        } catch (e: IOException) {
            e.printStackTrace()
            return ""
        }
    }
    override fun closeMvp() {
    }

    private var isHead = false
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_head -> {
                isHead = true
//                takePhoto()
                //单选
                PhotoSelector.builder().setSingle(true).start(this, 103)
                /*//单选后剪裁 裁剪的话都是针对一张图片所以要设置setSingle(true)
                PhotoSelector.builder()
                    .setSingle(true)//单选，裁剪都是单选
                    .setCrop(true)//是否裁剪
                    .setCropMode(PhotoSelector.CROP_RECTANG)//设置裁剪模式 矩形还是圆形
                    .setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .setToolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .setBottomBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                    .start(this, 103);*/
            }
            R.id.sm_study -> {
                sm_study.openMenu()
            }
            R.id.sm_iden -> {
                sm_iden.openMenu()
            }
            R.id.tv_submit -> {
                submitInfo()
            }

            R.id.iv_sex -> {//性别  feduSex家教中的性别 0.未知 1.男 2.女
                Alert.selectSex(this, "", "", "", "确定") { confirm, type ->
                    if (TextUtils.isEmpty(type)) {
                        ShowToast("请选择性别")
                        return@selectSex
                    }

                    if (confirm == CONFIRM) {
                        Alert.close()
                        //type=1男  =2女
                        if (type == "1") {
                            feduSex = "1"
                            tv_sex.text = "男"
                        } else if (type == "2") {
                            feduSex = "2"
                            tv_sex.text = "女"
                        }
//                        userInfo?.sex = sex.toInt()
//                        UserCache.save(userInfo)
                    }
                }
            }
        }
    }

}
